package com.chuanyang.driverh.mainhome;


import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.bean.AssignGoodData;
import com.chuanyang.driverh.bean.Waybill;
import com.chuanyang.driverh.mainhome.adapter.GoodsAssignAdapter;
import com.chuanyang.driverh.response2.ResultAllotGoods;
import com.chuanyang.driverh.response2.ResultGoodsAllotTop;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;
import com.chuanyang.driverh.utils.eventbus.FinishEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


public class GoodsAssignActivity extends BaseTitleActivity {
    private RadioGroup rg_top;
    private RadioButton rb0,rb1,rb2;
    private CheckBox  cb_all;
    private GoodsAssignAdapter listAdapter;
    private ListView lv_assigngoods;
    private String orderId;
    private TextView tv_clear,tv_choose_driver,tv_order_no;
//    private  DispatchOrderDetailData data;
    private OrderDetailData orderDetail;

    Waybill waybill;
    AssignGoodData goodsData;
    @Override
    protected int getContentResId() {
        return R.layout.home_act_assign_goods;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        rg_top=(RadioGroup)findViewById(R.id.rg_top);
        rb0=(RadioButton) findViewById(R.id.rb0);
        rb1=(RadioButton) findViewById(R.id.rb1);
        rb2=(RadioButton) findViewById(R.id.rb2);
        cb_all=(CheckBox) findViewById(R.id.cb_all);
        lv_assigngoods=(ListView) findViewById(R.id.lv_assigngoods);
        tv_clear=(TextView) findViewById(R.id.tv_clear);
        tv_choose_driver=(TextView) findViewById(R.id.tv_choose_driver);
        tv_order_no=(TextView) findViewById(R.id.tv_order_no);

    }

    @Override
    protected void initData() {
        rb0.setText("0"  +"\n"+"应分配重量");
        rb1.setText("0"+"\n"+"已分配重量");
        rb2.setText("0"+"\n"+"余分配重量");
        setBackImg();
        getTitleTextView().setText("货物分配");
//        getRightTextView().setText("筛选");
        orderId=getIntent().getStringExtra("data");
        tv_order_no.setText(orderId);
//        data = (DispatchOrderDetailData) getIntent().getSerializableExtra("data");
//        orderId=data.getOrderId();
        listAdapter=new GoodsAssignAdapter(activityContext);
        lv_assigngoods.setAdapter(listAdapter);
        getOrderdatail();
        getTopWeight();
    }



    @Override
    protected void initListener() {
        rb0.setOnClickListener(this);
        rb1.setOnClickListener(this);
        rb2.setOnClickListener(this);
        tv_clear.setOnClickListener(this);
        tv_choose_driver.setOnClickListener(this);
        cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            listAdapter.clearChoice(isChecked);
            }
        });
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.rb0:
                break;
            case R.id.rb1:
                break;
            case R.id.rb2:
                break;
            case R.id.tv_clear:
                cb_all.setChecked(false);
                listAdapter.clearChoice(false);
                break;
            case R.id.tv_choose_driver:
                try {
                    checkGoods();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void checkGoods() {


        ArrayList<Boolean> imgs=listAdapter.getImgs();
        ArrayList<String> assignWeight=listAdapter.getAssignWeight();

        goodsData=new AssignGoodData();
        ArrayList<AssignGoodData.WaybillDetailsData> waybillDetails=new ArrayList<>();
        for (int i=0;i<orderDetail.getDetailList().size();i++){
            if (imgs.size()>=i+1 && imgs.get(i)){
                AssignGoodData.WaybillDetailsData waybillDetail=new AssignGoodData.WaybillDetailsData();
                waybillDetail.setOrderdetailId(orderDetail.getDetailList().get(i).getOrderDetailId());
                if (StringUtil.isBlank(assignWeight.get(i))){
                    PrintUtil.toast(activityContext,"请填写所选货物的重量");
                    return;
                }else if(Double.parseDouble(assignWeight.get(i))==0){
                    PrintUtil.toast(activityContext,"请填写所选货物的重量");
                    return;
                }
                /*else if(Double.parseDouble(assignWeight.get(i))>Double.parseDouble(orderDetail.getDetailList().get(i).getSurplusWeight())){
                    PrintUtil.toast(activityContext,"分配的重量不能大于未分配重量");
                    return;
                }*/else{
                    waybillDetail.setDetailsWeight(assignWeight.get(i));
                }
                waybillDetails.add(waybillDetail);
            }
        }
        if (waybillDetails.size()>0){
            goodsData.setWaybillDetails(waybillDetails);
            startActivityForResult(new Intent(activityContext,ChooseDriverActivity.class),1);
        }else{
            PrintUtil.toast(activityContext,"请先选择货物分配");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data!=null && !StringUtil.isBlank(data.getStringExtra("data"))){
            goodsData.setDriverId(Integer.parseInt(data.getStringExtra("data")));
            waybill=new Waybill();
            waybill.setOrderId(orderDetail.getOrderId()+"");
            waybill.setWaybillParams(new ArrayList<AssignGoodData>() );
            waybill.getWaybillParams().add(goodsData);
            postAssignInfo(waybill);
        }

    }

    private void postAssignInfo(final Waybill waybill) {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
//        Map<String,String> params=new HashMap<String, String>();

        MyHttpUtil.AllotWaybill(activityContext,waybill, new MyCallback<ResultAllotGoods>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(ResultAllotGoods result, int id) {
                if (result.getCode() == ConstUtil.OK) {
//                    PrintUtil.toast(activityContext,"货物分配成功");
                    EventBusUtil.postEvent(new RefleshFragEvent(2));
                    initData();
                    if (result.getData()!=null)
                    startActivity(new Intent(activityContext,CarPlanSuccessActivity.class).putExtra("data",result.getData()+""));
                }else{
//                    PrintUtil.toast(activityContext,result.getMsg());
                }

            }
        });
    }

    private void getOrderdatail() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", orderId);
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.selectOrderMsgById(activityContext,params, new MyCallback<OrderDatailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    hideActivityLoading();
                    orderDetail = result.getData();
                    fillView(orderDetail);
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }
    private void getTopWeight() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("orderId", orderId);
        params.put("driverId", SharedPrefUtil.getUserId());
        MyHttpUtil.getDispatchInfoByOrderId(activityContext,params, new MyCallback<ResultGoodsAllotTop>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(ResultGoodsAllotTop result, int id) {
                if (result.getCode() == ConstUtil.OK) {
//                    fillView(orderDetail);

                    fillTop(result.getData());
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });



    }

    private void fillTop(ResultGoodsAllotTop.DataBean data){
        rb0.setText(StringUtil.getDouble(data.getSumDetailsWeight()+"")  +"\n"+"应分配重量");
        rb1.setText(StringUtil.getDouble(data.getThenDispatchSumWeigth()+"")+"\n"+"已分配重量");
        rb2.setText(StringUtil.getDouble(data.getSurplusSumWeight()+"")+"\n"+"余分配重量");
    }
    private void fillView(OrderDetailData orderDetail) {
        if (orderDetail==null)return;


        tv_order_no.setText(orderDetail.getOrderNo());
        listAdapter.clear();
        listAdapter.addAll( orderDetail.getDetailList());
        listAdapter.notifyDataSetChanged();
    }

    public void onEventMainThread(FinishEvent event) {
        if (event.getIndex()==1  ){
          finish();
        }
    }
}
